package client_gui_chat;

import static client.ClientApplication.clientBinding;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import client.ClientBindObject;


/**
 * Klasa upravlja dogadjajima prozora chat dialoga.
 * 
 * @author UrosKrkic & Radivoje Popovic
 */
public class ChatWindowHandler extends WindowAdapter {

	/**
	 * Prozor chat dialoga.
	 */
	private ChatDialog owner;
	
	
	/**
	 * Konstruktor.
	 * @param owner - prozor chat dialoga cijim se dogadjajima rukuje
	 * @author UrosKrkic & Radivoje Popovic
	 */
	public ChatWindowHandler(ChatDialog owner) {
		this.owner = owner;
	}
	
	
	@Override
	public void windowClosing(WindowEvent e) {
		
		new Thread(new Runnable() {
			@Override
			public void run() {
				ClientBindObject cbo = clientBinding.get(owner.getUser().getUsername());
				
				if (cbo != null && cbo.getDialog() != null) {
					if ( !cbo.isConnectionActive()) {
						clientBinding.remove(owner.getUser().getUsername());
					}
					if ( owner.getConnection() != null ) {
						owner.getConnection().writeData("PEER_TYPING " + owner.getClientUser().getUsername() + " " + false);
						owner.getStreamingPanel().getNoButton().doClick();
						owner.getStreamingPanel().getStopCallButton().doClick();
					}
					cbo.setChatDialogConnection(null);
					cbo.getDialog().getStreamingPanel().removeListeners();
					cbo.setChatDialog(null);
					if ( cbo.getCall() != null ) {
						cbo.getCall().hangUpCall();
						cbo.setCall(null);
					}
				}
			}
		}).start();
		
		owner.stopTypingListener();
		
		owner.dispose();
	}
	
	
}
